package mysql_learn;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class 没有事务 {

    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/sprintboot-test?useSSL=false";
    private static final String JDBC_USER = "root";
    private static final String JDBC_PASSWORD = "2002";

    public static void main(String[] args) {
        Connection connection = null;

        try {
            // 1. 加载MySQL JDBC驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. 创建数据库连接
            connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);


            // 4. 执行SQL语句
            String sql1 = "INSERT INTO user (username, password, name, age, avatar) VALUES (?, ?, ?, ?, ?)";
            PreparedStatement pstmt1 = connection.prepareStatement(sql1);
            pstmt1.setString(1, "long666666666");
            pstmt1.setString(2, "123456666666666");
            pstmt1.setString(3, "Luogeng6666666");
            pstmt1.setInt(4, 25);
            pstmt1.setString(5, "https://www.example.com/avatar.jpg");
            pstmt1.executeUpdate();

            // 暂停执行 10 秒钟，模拟事务执行时间
            Thread.sleep(10000);

            String sql2 = "UPDATE bubu  SET name= ? WHERE username = ?";
            PreparedStatement pstmt2 = connection.prepareStatement(sql2);
            pstmt2.setString(1, "毛泽东");
            pstmt2.setString(2, "123");
            pstmt2.executeUpdate();


            System.out.println("全部执行成功！");

        } catch (Exception e) {
            System.out.println("发生异常:");
            e.printStackTrace();
        } finally {
            // 6. 关闭资源
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException closingException) {
                    System.err.println("无法关闭数据库连接: " + closingException.getMessage());
                }
            }
        }

    }
}

